// plugin/gatsby-source-mystrapi/gatsby-node.js
const axios = require('axios')
const pluralize = require('pluralize')
const createNodeHelper = require('gatsby-node-helpers').default

async function sourceNodes ({actions}, configOptions) {
    const { createNode } = actions
    const { apiUrl, contentTypes } = configOptions
    // Post -> posts  Product -> products 使用 pluralize 模块转换
    const types = contentTypes
        .map(type => type.toLowerCase())
        .map(type => pluralize(type))
    console.log(types) // ['posts', 'products']
    
    let final = await getContents(types, apiUrl) // 数据
    for (let [key, value] of Object.entries(final)) {
        // 1. 构建数据节点对象
        const {createNodeFactory} = createNodeHelper({
            typePrefix: key // 数据节点类型前缀 posts products
        })
        const createNodeObject = createNodeFactory('content') // 后缀 allPostsContent allProductsContent
        // 2. 根据数据节点对象创建节点
        value.forEach(item => {
            // 使用 createNodeObject 方法构建数据节点对象
            // 使用 createNode 方法构建数据节点
            createNode(createNodeObject(item))
        })
    }
}

// 从外部数据源中获取数据
function getContents (types, apiUrl) {
    const size = types.length
    let index = 0
    const final = {}
    // 初始调用
    loadContents()
    async function loadContents () {
        if (index === size) return
        const { data } = await axios.get(`${apiUrl}/${types[index]}`)
        final[types[index++]] = data
        await loadContents()
    }

    return final
}

module.exports = {
    sourceNodes
}